package com.atguigu.gmall.order.listener;

import com.atguigu.gmall.common.constant.RabbitConstant;
import com.atguigu.gmall.common.util.JSONs;
import com.atguigu.gmall.model.mq.to.ware.WareDeductMsg;
import com.atguigu.gmall.mq.service.RabbitService;
import com.atguigu.gmall.order.service.OrderInfoService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
@Slf4j
public class OrderDeductListener {
    @Autowired
    RabbitService rabbitService;

    @Autowired
    OrderInfoService orderInfoService;


    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue(value = RabbitConstant.QUEUE_ORDER_DEDUCT, durable = "true",
                            exclusive = "false", autoDelete = "false"),
                    exchange = @Exchange(name = RabbitConstant.EXCHANGE_WARE_ORDER,
                            type = ExchangeTypes.TOPIC),
                    key = RabbitConstant.RK_ORDER_WARE
            )
    )
    public void handleDeduct(Message message, Channel channel) throws IOException {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        String json = new String(message.getBody());
        try {

            WareDeductMsg msg = JSONs.stringToObj(json, WareDeductMsg.class);
            orderInfoService.updateOrderStock(msg);

            channel.basicAck(deliveryTag, false);


        } catch (Exception e) {
            log.info("消息{}发送失败",json);
            rabbitService.retry(deliveryTag, channel, json, 5);
        }
    }
}
